//
//  KAContactVC.swift
//  kano
//
//  Created by Sophia on 2024/8/22.
//

import UIKit
import Contacts
import ContactsUI
import PopupDialog

class KAContactVC: KABaseVC, UIScrollViewDelegate {
    
    let kname = "name"
    let knumber = "mobile"
    let kstate = "state"
    
    var var_relationships: [String] = ["Father", "Mother", "Spouse"]
    var var_currentSection: Int? = -1
    
    var applyModel: KAApply
    var var_pageModel: KAApplyPageElement?
    var var_model: KAContact = KAContact()
    var var_basicModel: KABasic?
    
    let halfWidth: CGFloat = (var_screenWidth-kscale(50))/2
    let cellHeight: CGFloat = kscale(46)
    
    lazy var var_scrollView: UIScrollView = {
        let var_scrollView = UIScrollView(frame: CGRectMake(0, UIDevice.ka_fullNavHeight, view.width, UIDevice.ka_viewHeight))
        var_scrollView.backgroundColor = .colorFFF
        var_scrollView.isScrollEnabled = true
        var_scrollView.contentSize = CGSize(width: var_screenWidth, height: var_screenHeight)
        var_scrollView.bounces = true
        var_scrollView.delegate = self
        return var_scrollView
    }()
    
    
    lazy var var_contact1Title: UILabel = {
        let var_contact1Title = UILabel()
        var_contact1Title.isUserInteractionEnabled = true
        var_contact1Title.font = UIFont.systemFont(ofSize: kscale(14), weight: .bold)
        var_contact1Title.textColor = .black
        var_contact1Title.text = "Contact1"
        var_contact1Title.numberOfLines = 1
        var_contact1Title.frame = CGRect(x: kscale(20), y: kscale(16), width: view.width-kscale(40), height: kscale(20))
        return var_contact1Title
    }()
    lazy var var_contact2Title: UILabel = {
        let var_contact2Title = UILabel()
        var_contact2Title.isUserInteractionEnabled = true
        var_contact2Title.font = UIFont.systemFont(ofSize: kscale(14), weight: .bold)
        var_contact2Title.textColor = .black
        var_contact2Title.text = "Contact2"
        var_contact2Title.numberOfLines = 1
        var_contact2Title.frame = CGRect(x: kscale(20), y: var_contact1Tel.bottom+kscale(20), width: view.width-kscale(40), height: kscale(24))
        return var_contact2Title
    }()
    lazy var var_contact3Title: UILabel = {
        let var_contact3Title = UILabel()
        var_contact3Title.isUserInteractionEnabled = true
        var_contact3Title.font = UIFont.systemFont(ofSize: kscale(14), weight: .bold)
        var_contact3Title.textColor = .black
        var_contact3Title.text = "Contact3"
        var_contact3Title.numberOfLines = 1
        var_contact3Title.frame = CGRect(x: kscale(20), y: var_contact2Tel.bottom+kscale(20), width: view.width-kscale(40), height: kscale(24))
        return var_contact3Title
    }()
    
    
    lazy var var_contact1Cell: KAContactView = {
        let var_contact1Cell = KAContactView(frame: CGRectMake(kscale(20), var_contact1Title.bottom+kscale(10), view.width-kscale(40), cellHeight), type: .arrow)
        var_contact1Cell.contentTF.placeholder = "Relationship"
        var_contact1Cell.tag = 1
        let var_tap = UITapGestureRecognizer(target: self, action: #selector(ka_showRelationship(_ :)))
        var_contact1Cell.addGestureRecognizer(var_tap)
        return var_contact1Cell
    }()
    lazy var var_contact2Cell: KAContactView = {
        let var_contact2Cell = KAContactView(frame: CGRectMake(kscale(20), var_contact2Title.bottom+kscale(10), view.width-kscale(40), cellHeight), type: .arrow)
        var_contact2Cell.contentTF.placeholder = "Relationship"
        var_contact2Cell.tag = 2
        let var_tap = UITapGestureRecognizer(target: self, action: #selector(ka_showRelationship(_ :)))
        var_contact2Cell.addGestureRecognizer(var_tap)
        return var_contact2Cell
    }()
    lazy var var_contact3Cell: KAContactView = {
        let var_contact3Cell = KAContactView(frame: CGRectMake(kscale(20), var_contact3Title.bottom+kscale(10), view.width-kscale(40), cellHeight), type: .arrow)
        var_contact3Cell.contentTF.text = "Friend"
        //置灰，不能选
//        var_contact3Cell.contentTF.textColor = .lightGray
//        var_contact3Cell.var_rightBtn.setImage(UIImage(named: "cell_arrow")?.withTintColor(.lightGray), for: .normal)
        return var_contact3Cell
    }()
    
    
    lazy var var_contact1Name: KAContactView = {
        let var_contact1Name = KAContactView(frame: CGRectMake(kscale(20), var_contact1Cell.bottom+kscale(10), halfWidth, cellHeight), type: .clear)
        var_contact1Name.contentTF.placeholder = "Name"
        var_contact1Name.var_index = 0
        return var_contact1Name
    }()
    lazy var var_contact2Name: KAContactView = {
        let var_contact2Name = KAContactView(frame: CGRectMake(kscale(20), var_contact2Cell.bottom+kscale(10), halfWidth, cellHeight), type: .clear)
        var_contact2Name.contentTF.placeholder = "Name"
        var_contact2Name.var_index = 1
        return var_contact2Name
    }()
    lazy var var_contact3Name: KAContactView = {
        let var_contact3Name = KAContactView(frame: CGRectMake(kscale(20), var_contact3Cell.bottom+kscale(10), halfWidth, cellHeight), type: .clear)
        var_contact3Name.contentTF.placeholder = "Name"
        var_contact3Name.var_index = 2
        return var_contact3Name
    }()
    
    
    lazy var var_contact1Tel: KAContactView = {
        let var_contact1Tel = KAContactView(frame: CGRectMake(var_contact1Name.right+kscale(10), var_contact1Cell.bottom+kscale(10), halfWidth, cellHeight), type: .contact)
        var_contact1Tel.contentTF.placeholder = "Telephone"
        var_contact1Tel.tag = 1
        if applyModel.authorizedEntityList == "1" {
            var_contact1Tel.contentTF.isUserInteractionEnabled =  true
        }
        let var_tap = UITapGestureRecognizer(target: self, action: #selector(ka_showContactPickerVC(_ :)))
        var_contact1Tel.var_rightBtn.tag = 1
        var_contact1Tel.var_rightBtn.addGestureRecognizer(var_tap)
        return var_contact1Tel
    }()
    lazy var var_contact2Tel: KAContactView = {
        let var_contact2Tel = KAContactView(frame: CGRectMake(var_contact2Name.right+kscale(10), var_contact2Cell.bottom+kscale(10), halfWidth, cellHeight), type: .contact)
        var_contact2Tel.contentTF.placeholder = "Telephone"
        var_contact2Tel.tag = 2
        if applyModel.authorizedEntityList == "1" {
            var_contact2Tel.contentTF.isUserInteractionEnabled =  true
        }
        let var_tap = UITapGestureRecognizer(target: self, action: #selector(ka_showContactPickerVC(_ :)))
        var_contact2Tel.var_rightBtn.tag = 2
        var_contact2Tel.var_rightBtn.addGestureRecognizer(var_tap)
        return var_contact2Tel
    }()
    lazy var var_contact3Tel: KAContactView = {
        let var_contact3Tel = KAContactView(frame: CGRectMake(var_contact3Name.right+kscale(10), var_contact3Cell.bottom+kscale(10), halfWidth, cellHeight), type: .contact)
        var_contact3Tel.contentTF.placeholder = "Telephone"
        var_contact3Tel.tag = 3
        if applyModel.authorizedEntityList == "1" {
            var_contact3Tel.contentTF.isUserInteractionEnabled =  true
        }
        let var_tap = UITapGestureRecognizer(target: self, action: #selector(ka_showContactPickerVC(_ :)))
        var_contact3Tel.var_rightBtn.tag = 3
        var_contact3Tel.var_rightBtn.addGestureRecognizer(var_tap)
        return var_contact3Tel
    }()
    
    
    lazy var var_nextBtn: UIButton = {
        let var_nextBtn = UIButton(frame: CGRectMake(kscale(20), var_contact3Tel.bottom+kscale(20), var_screenWidth-kscale(40), kscale(50.0)))
        var_nextBtn.setTitle("Next", for: .normal)
        var_nextBtn.setTitleColor(.white, for: .normal)
        var_nextBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(17), weight: .bold)
        var_nextBtn.backgroundColor = .themeColor
        var_nextBtn.layer.cornerRadius = kscale(25)
        var_nextBtn.layer.masksToBounds = true
        var_nextBtn.addTarget(self, action: #selector(ka_nextBtnClick), for: .touchUpInside)
        return var_nextBtn
    }()
    
    var pickerSources: [KAPickerData] = []
    
    override func customNavBackAction() {
        for vc in navigationController!.viewControllers {
            if vc.isKind(of: KAInfoVC.self) {
                let infoVC = vc as! KAInfoVC
                navigationController?.popToViewController(infoVC, animated: true)
                return
            }
        }
        navigationController?.popViewController(animated: true)
    }
    
    init(model: KAApply) {
        applyModel = model
        //        let submit = model.creditElement?.creditResult.kj.model(KAApplySubmit.self)
        //        var_model = submit?.contact
        //页面信息
        var_pageModel = model.creditElement?.pageElements?.last
        //处理回显数据
        let dicResult = dealStringToObject(with: model.creditElement?.creditResult) as? [String : Any]
        let submitDic = dicResult?["contact"] as? String
        if submitDic != nil {
            let submit = submitDic!.kj.model(KAContact.self)
            var_model = submit!
        }
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

extension KAContactVC {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let data = KAPageInfo(eleId: "sx_acv_contact", path: "\(KAContactVC.self)")
        KAReport.ka_reportWith(type: .page, data: data.kj.JSONObject())
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        ht_setUI()
        ht_loadPickerList()
//        ka_showAlert()
    }
    
    func ka_showAlert() {
        let content = """
        Please note that we will send a message to the contacts you provide to request their consent.  They can only be listed as your emergency contacts if they agree.  If they do not consent, we will delete their data and will not contact them again.  This may affect your credit eligibility, so please communicate with your provided contacts promptly.
        In special circumstances, we will prioritize contacting you directly.  If we cannot reach you, we will only contact the emergency contacts you provided and who have consented in case of emergencies.  Additionally, we will not sell, trade, or rent your information or that of your contacts to any third parties.
"""
        let alertVC = KAContactAlertVC(title: "Emergency Contact Information Statement", subTitle: content, actionTitle: "Got it")
        let popup = PopupDialog(viewController: alertVC, buttonAlignment: .horizontal, transitionStyle: .zoomIn, tapGestureDismissal: true, panGestureDismissal: false)
        alertVC.handler = {
            popup.dismiss()
        }
        let containerAppearance = PopupDialogContainerView.appearance()
        containerAppearance.cornerRadius = 20
        self.present(popup, animated: true, completion: nil)
    }
    
    func ht_setUI() {
        view.backgroundColor = .white
        view.addSubview(var_scrollView)
        var_scrollView.addSubview(var_contact1Title)
        var_scrollView.addSubview(var_contact1Cell)
        var_scrollView.addSubview(var_contact1Name)
        var_scrollView.addSubview(var_contact1Tel)
        var_scrollView.addSubview(var_contact2Title)
        var_scrollView.addSubview(var_contact2Cell)
        var_scrollView.addSubview(var_contact2Name)
        var_scrollView.addSubview(var_contact2Tel)
        var_scrollView.addSubview(var_contact3Title)
        var_scrollView.addSubview(var_contact3Cell)
        var_scrollView.addSubview(var_contact3Name)
        var_scrollView.addSubview(var_contact3Tel)
        var_scrollView.addSubview(var_nextBtn)
        
        ka_showCustomerNavBar(type: .normal)
        var_navBar.var_titleLabel.text = "Obtain credit limit"
        
        var_contact1Cell.contentTF.text = var_model.relation1.label
        var_contact1Tel.contentTF.text = var_model.phoneNo1.phone
        var_contact1Name.contentTF.text = var_model.phoneNo1.name
        
        var_contact2Cell.contentTF.text = var_model.relation2.label
        var_contact2Tel.contentTF.text = var_model.phoneNo2.phone
        var_contact2Name.contentTF.text = var_model.phoneNo2.name
        
        var_contact3Cell.contentTF.text = var_model.relation3.label
        var_contact3Tel.contentTF.text = var_model.phoneNo3.phone
        var_contact3Name.contentTF.text = var_model.phoneNo3.name
    }
    
    func ht_loadPickerList() {
        let model = var_pageModel?.elements?.first
        let paramDic = [
            "taskId" : var_pageModel?.taskId ?? "",
            "fieldId" : model?.fieldId ?? "",
        ] as [String : Any]
        applyProvider.request(.pikerSources(paramDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    ApplyResponse<[KAPickerData]>.handleApplyResponse(response.data) { isSuccess, message, response in
                        if isSuccess {
                            pickerSources = (response?.data)!
                        }
                    }
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
    @objc func ka_showRelationship(_ sender: UITapGestureRecognizer) {
        view.endEditing(true)
        if let tappedView = sender.view {
            var_currentSection = tappedView.tag
            //按钮埋点
            if var_currentSection == 1 {
                let btnInfo = KABtnInfo(eleId: "sx_acb_contact_firstRelation", pageId: "sx_acv_contact", clickTime: Date.ka_currentData())
                KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            } else if var_currentSection == 2 {
                let btnInfo = KABtnInfo(eleId: "sx_acb_contact_spareRelation", pageId: "sx_acv_contact", clickTime: Date.ka_currentData())
                KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            }
            
            if (pickerSources.count == 0) {
                ht_loadPickerList()
            }
            var_relationships = pickerSources.map { $0.value }
            KAPickerView.ka_showStringPicker(title: "", dataSources: var_relationships, selectValue: var_relationships.first) { [self] select in
                guard let index = var_relationships.firstIndex(where: { $0.hasPrefix(select) }) else {
                    return
                }
                let pickerModel = pickerSources[index]
                
                if var_currentSection == 1 {
                    var_contact1Cell.contentTF.text = select
                    var_model.relation1.parentId = pickerModel.id
                    var_model.relation1.parentId = 0
                    var_model.relation1.label = pickerModel.value
                    var_model.relation1.report = pickerModel.report
                    
                } else if var_currentSection == 2 {
                    var_contact2Cell.contentTF.text = select
                    var_model.relation2.parentId = pickerModel.id
                    var_model.relation2.parentId = 0
                    var_model.relation2.label = pickerModel.value
                    var_model.relation2.report = pickerModel.report
                    
                } else if var_currentSection == 3 {
                    var_contact3Cell.contentTF.text = select
                    var_model.relation3.parentId = pickerModel.id
                    var_model.relation3.parentId = 0
                    var_model.relation3.label = pickerModel.value
                    var_model.relation3.report = pickerModel.report
                }
            }
        }
    }
    
    @objc func ka_showContactPickerVC(_ sender: UITapGestureRecognizer) {
        if let tappedView = sender.view {
            view.endEditing(true)
            let controller = CNContactPickerViewController()
            controller.delegate = self
            var_currentSection = tappedView.tag
            present(controller, animated: true, completion: nil)
            
            //按钮埋点
            if var_currentSection == 1 {
                let btnInfo = KABtnInfo(eleId: "sx_acb_contact_first_details", pageId: "sx_acv_contact", clickTime: Date.ka_currentData())
                KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            } else if var_currentSection == 2 {
                let btnInfo = KABtnInfo(eleId: "sx_acb_contact_spare_details", pageId: "sx_acv_contact", clickTime: Date.ka_currentData())
                KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            } else if var_currentSection == 3 {
                let btnInfo = KABtnInfo(eleId: "sx_acb_contact_third_details", pageId: "sx_acv_contact", clickTime: Date.ka_currentData())
                KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            }
        }
    }
    
    func checkRelationShip(_ string: String) -> Bool {
        if string == "Father" || string == "Mother" || string == "Wife" || string == "Husband" {
            return true
        }
        return false
    }
    
    @objc func ka_nextBtnClick() {
        if var_model.relation1.label.isEmpty || var_model.relation2.label.isEmpty || var_model.phoneNo1.phone.isEmpty || var_model.phoneNo2.phone.isEmpty || var_model.phoneNo3.phone.isEmpty {
            view.makeToast("Please complete the information"); return
        }
//        if !checkRelationShip(var_model.relation1.label) || !checkRelationShip(var_model.relation2.label) {
//            view.makeToast("Contact relationship must be spouse, father, mother two items, please check and re-submit"); return
//        }
        if var_model.relation1.label == var_model.relation2.label {
            view.makeToast("The relationship between Contact1 and Contact2 is repeated"); return
        }
        if var_model.phoneNo1.phone == KAUserManager.shared.user.mobile || var_model.phoneNo2.phone == KAUserManager.shared.user.mobile || var_model.phoneNo3.phone == KAUserManager.shared.user.mobile {
            view.makeToast("Please do not enter your own phone number"); return
        }
        
        if var_model.phoneNo1.phone == var_model.phoneNo2.phone || var_model.phoneNo1.phone == var_model.phoneNo3.phone || var_model.phoneNo2.phone == var_model.phoneNo3.phone {
            view.makeToast("The contact number is repeated. Select another contact"); return
        }
        
        let btnInfo = KABtnInfo(eleId: "sx_acb_contact_all_next", pageId: "sx_acv_contact", clickTime: Date.ka_currentData())
        KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        
        let contactsInfo: [Dictionary<String, Any>] = [
            ["pricingInfo" : var_model.relation1.label, "additionalRemarks" : var_model.phoneNo1.name, "phoneContactNumber" : var_model.phoneNo1.phone],
            ["pricingInfo" : var_model.relation2.label, "additionalRemarks" : var_model.phoneNo2.name, "phoneContactNumber" : var_model.phoneNo2.phone],
            ["pricingInfo" : var_model.relation3.label, "additionalRemarks" : var_model.phoneNo3.name, "phoneContactNumber" : var_model.phoneNo3.phone],
        ]
        
        let cacheDic: [String : Any] = [
            "userGid" : KAUserManager.shared.user.userGid,
            "loanStatementList" : "contact",
            "value" : var_model.kj.JSONString()
        ]
        applyProvider.request(.cache(cacheDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    let vc = KAInfoExtVC(model: applyModel)
                    vc.var_basicModel = var_basicModel
                    vc.var_contactModel = var_model
                    vc.var_contactArray = contactsInfo
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}

extension KAContactVC: CNContactPickerDelegate {
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
//        let name = "\(contact.familyName)\(contact.givenName)"
        //格式化联系人信息,将CNContact对象格式化为字符串
        let name = CNContactFormatter.string(from: contact, style: CNContactFormatterStyle.fullName)
        var contactArray: [String] = []
        for phone in contact.phoneNumbers {
            var phoneStr = (phone.value as CNPhoneNumber).stringValue
            phoneStr = phoneStr.replacingOccurrences(of: "-", with: "")
            //            let cleaned = phoneStr.components(separatedBy: CharacterSet.whitespaces).joined()
            var cleaned = phoneStr.cleanedNumber()
            let correct = cleaned.correctNumber()
            contactArray.append(correct)
        }
        
        if contactArray.count > 1 {
            KAPickerView.ka_showStringPicker(title: "", dataSources: contactArray, selectValue: contactArray.first) { select in
                self.dealDataWith(name ?? "", select)
            }
        } else {
            dealDataWith(name ?? "", contactArray.first ?? "")
        }
    }
    
    func dealDataWith(_ name: String, _ phone: String) {
        if !phone.verifyPhone {
            view.makeToast("Contact \(var_currentSection!) Phone Number Format Is Incorrect")
            return
        }
        if var_currentSection == 1 {
            var_model.phoneNo1.name = name
            var_model.phoneNo1.phone = phone
            var_contact1Tel.contentTF.text = phone
            var_contact1Name.contentTF.text = name
        } else if var_currentSection == 2 {
            var_model.phoneNo2.name = name
            var_model.phoneNo2.phone = phone
            var_contact2Tel.contentTF.text = phone
            var_contact2Name.contentTF.text = name
        } else if var_currentSection == 3 {
            var_model.phoneNo3.name = name
            var_model.phoneNo3.phone = phone
            var_contact3Tel.contentTF.text = phone
            var_contact3Name.contentTF.text = name
        }
    }
}
